package com.atelier.plugin.database.action;

import com.atelier.plugin.database.domain.DatabaseConnectionInfo;
import com.atelier.plugin.database.ui.DataSourceSettingDialog;
import com.atelier.plugin.projectWizard.util.ICONS;
import com.atelier.plugin.service.DataBaseConnectionStorageService;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.ui.components.JBList;

import javax.swing.*;
import java.util.List;

public class RemoveConnectionAction extends DumbAwareAction {
    private DataSourceSettingDialog dialog;

    public RemoveConnectionAction() {
        super("Remove", "Delete", ICONS.REMOVE);
    }

    public RemoveConnectionAction(DataSourceSettingDialog dialog) {
        super("Remove", "Delete", AllIcons.General.Remove);
        this.dialog = dialog;
    }

    @Override
    public void actionPerformed(AnActionEvent event) {
        if (dialog == null) {
            return;
        }

        DefaultListModel<DatabaseConnectionInfo> listModel = dialog.getListModel();
        JBList<DatabaseConnectionInfo> datasouceList = dialog.getDatasouceList();

        if (listModel == null || datasouceList == null) {
            return;
        }

        List<DatabaseConnectionInfo> selectedValuesList = datasouceList.getSelectedValuesList();
        if (selectedValuesList.isEmpty()) {
            return;
        }

        // 仅修改 listModel，不修改数据源
        for (DatabaseConnectionInfo connectionInfo : selectedValuesList) {
            listModel.removeElement(connectionInfo);
        }
        // 设置新的光标位置
        if(listModel.getSize()!=0) {
            DatabaseConnectionInfo elementAt = listModel.getElementAt(listModel.size() - 1);
            DataSourceSettingDialog.getInstance().getDatasouceList().setSelectedValue(elementAt, true);
        }
        datasouceList.setModel(listModel);
    }
}
